package com.voute.Utils;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.orhanobut.logger.Logger;
import com.voute.App.App;
import com.voute.Consts.Constants;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by liukanshan on 2016/12/8.
 */

public class ServiceFactory {

    private static ServiceFactory instance;

    public static ServiceFactory GetInstance() {
        synchronized (ServiceFactory.class) {
            if (instance == null) {
                instance = new ServiceFactory();
            }
        }
        return instance;
    }

    public <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(serviceClass);
    }

    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //设置超时时间以及App拦截器
        builder.connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Logger.d("Sending request %s on %s%n%s,body%s", originalRequest.url(), chain.connection(), originalRequest.headers(), originalRequest.body());
                /**
                 * OS=iOS&Release=10.2&Model=iPhone9,1&VersionName=3.28.0&VersionCode=558&Width=750&Height=1334
                 */
                String app_bt_string = "OS=Android&Release=" + android.os.Build.VERSION.RELEASE + "&Model=" + android.os.Build.MODEL + "&VersionName=" + DeviceUtils.getVersionName() + "&VersionCode=" + DeviceUtils.getVersionCode() + "&Width=" + DisplayUtil.GetDisplayWidth() + "&Height=" + DisplayUtil.GetDisplayHeight();
                String device_id = ((TelephonyManager) App.GetInstance().getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
                if (TextUtils.isEmpty(device_id)) {
                    device_id = "";
                }
                Request compressedRequest = originalRequest.newBuilder()
                        //认证信息统一放在头部中
                        .header("Authorization", "Bearer " + PreferenceUtils.GetUserToken())
                        .header("Content-Type", "application/json; charset=utf-8")
                        .header("x-app-bt", app_bt_string)
                        .header("x-app-device", device_id)
                        .build();
                Response originalResponse = chain.proceed(compressedRequest);
                String body = originalResponse.body().string();
                Logger.json(body);
                return originalResponse.newBuilder()
                        .body(ResponseBody.create(MediaType.parse("UTF-8"), body))
                        .build();
            }
        });
        return builder.build();
    }
}
